package chatspace.dao;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import chatspace.entities.Discussion;
import chatspace.entities.User;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author GHANEMEL
 */
public class Dao {

    private EntityManagerFactory emf = null;
    EntityManager em = null;
    //private Logger //logger = Logger.getLogger(Dao.class.getName());

    public Dao() {
        emf = Persistence.createEntityManagerFactory("chatspacePU");
        em = emf.createEntityManager();
    }

    public void begin() {
        em = emf.createEntityManager();
        em.getTransaction().begin();
    }

    public Boolean isActive() {
        return em.getTransaction().isActive();
    }

    public void commit() {
        em.getTransaction().commit();
    }

    public void rollback(int a) {
        em.getTransaction().rollback();
    }

    public EntityManager getEntityManager() {
        return em;
    }

    public void create(Object obj) {
        em.persist(obj);
    }

    public Object edit(Object obj) {
        return em.merge(obj);
    }

    public Object find(Object obj, Long id) {
        Object r = null;
        try {
            r = em.find(obj.getClass(), id);
        } catch (NoResultException ex) {
            //logger.info("Aucun objet " + obj + " avec id=" + id + " n'a été trouvé.");
        }
        return r;
    }

    public List findListWithCriteres(String obj, String critere) {
        Query q = em.createQuery("select object(o) from " + obj + " as o where " + critere);
        return q.getResultList();
    }

    public List findAll(String obj) {
        try {
            Query q = em.createQuery("select object(o) from " + obj + " as o");
            return q.getResultList();
        } catch (NoResultException ex) {
            //logger.info("Aucun objet " + obj + " n'a été trouvé.");
            return new ArrayList();
        }
    }

    public int count(String obj) {
        Query q = em.createQuery("select count(o) from " + obj + " as o");
        return ((Long) q.getSingleResult()).intValue();
    }

    public List findRange(int maxResults, int firstResult, String entity) {
        return findRange(false, maxResults, firstResult, entity);
    }

    private List findRange(boolean all, int maxResults, int firstResult, String entity) {
        try {
            Query q = em.createQuery("select object(o) from " + entity + " as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } catch (NoResultException ex) {
            //logger.info("Aucun objet " + entity + " n'a été trouvé.");
            return new ArrayList();
        }
    }

    public Object findWithCriteres(String obj, String critere) {
        try {
            Query q = em.createQuery("select object(o) from " + obj + " as o where " + critere);
            return q.getSingleResult();
        } catch (NoResultException ex) {
            //logger.info("Aucun objet " + obj + " avec critères " + critere + " n'a été trouvé.");
            return null;
        }
    }

    public List<Discussion> findDiscussionByUsers(User connectedUser, User advUser, int start, int end) {
        String hql = "select d from Discussion d where (d.user=:u and d.toUser=:tU) or (d.user=:tU and d.toUser=:u) order by d.dt desc";
        Query q = em.createQuery(hql);
        q.setParameter("u", connectedUser);
        q.setParameter("tU", advUser);
        q.setFirstResult(start);
        q.setMaxResults(end - start);
        
        return q.getResultList();
    }

    public User findUserByLoginAndPassword(String login, String password) {
        String hql = "select u from User u where u.login=:l and u.password=:p";
        Query q = em.createQuery(hql);

        q.setParameter("l", login);
        q.setParameter("p", password);

        try {
            return (User) q.getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    public List<User> searchForUsers(String searchFor) {
        if("".equals(searchFor)){
            return findAll("User");
        }
        String hql = "select u from User u where (u.firstname like :s or u.lastname like :s)";
        Query q = em.createQuery(hql);
        q.setParameter("s", "%"+searchFor+"%");
        return q.getResultList();
    }
    
}
